import { Component, Prop, Inject } from 'vue-property-decorator';

import {
  ConfigType,
  ValueChecker,
  ViewFieldDescriptor,
  ObjectViewContext,
  isBoolean,
  includes,
} from '../../vendors/handie';

import BaseHeadlessWidget from '../base';

@Component
export default class FieldHeadlessWidget<ValueType = any> extends BaseHeadlessWidget {
  @Inject({ from: 'viewContext', default: null })
  protected readonly context!: ObjectViewContext;

  @Prop({ type: Object, default: () => ({}) })
  protected readonly field!: ViewFieldDescriptor;

  protected get config(): ConfigType {
    return this.field.config || {};
  }

  protected get showValidationRulesAsNative(): boolean {
    const { showFieldValidationRulesAsNative } = this.context.getConfig();

    return isBoolean(showFieldValidationRulesAsNative)
      ? showFieldValidationRulesAsNative
      : this.getCommonBehavior('field.showValidationRulesAsNative', false);
  }

  protected getPlaceholder(): string {
    let { showHintAsPlaceholder } = this.config;

    if (showHintAsPlaceholder === undefined) {
      showHintAsPlaceholder = this.getCommonBehavior('field.showHintAsPlaceholder');
    }

    let defaultPlaceholder: string = '';

    if (this.field.dataType) {
      defaultPlaceholder = `${
        includes(this.field.dataType, ['string', 'text', 'int', 'float']) ? '请输入' : '请选择'
      }${this.field.label || ''}`;
    }

    const placeholder = this.field.placeholder || defaultPlaceholder;

    return showHintAsPlaceholder ? this.field.hint || placeholder : placeholder;
  }

  protected setValueChecker(checker: ValueChecker): void {
    this.context.setFieldChecker(this.field.name, checker);
  }

  protected onChange(value: ValueType): void {
    this.$emit('change', value);
  }
}
